/*******************************************************************************
 * Copyright (c) 2009-2011 ETCORE Labs. All rights reserved. 
 * 
 * This software is the confidential and proprietary information of ETCORE Labs.
 * You shall not disclose such confidential information and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with ETCORE Labs. 
 * 
 * Support can be obtained from support forums at:  http://www.etcore.com/
 * /
 *******************************************************************************/
package etcore.webapp.grouptalk.user.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import etcore.webapp.grouptalk.common.action.AbstractAction;
import etcore.webapp.grouptalk.common.config.Config;
import etcore.webapp.grouptalk.common.config.MessageNamespaces;
import etcore.webapp.grouptalk.common.config.PageConstants;
import etcore.webapp.grouptalk.common.object.Attachment;
import etcore.webapp.grouptalk.common.object.Comment;
import etcore.webapp.grouptalk.common.service.AttachmentService;
import etcore.webapp.grouptalk.common.service.MessageService;
import etcore.webapp.grouptalk.user.object.User;
import etcore.webapp.grouptalk.user.service.UserService;
import etcore.webapp.grouptalk.util.Symbols;

/**
 * This action validates the request and executes the command of getting my
 * messages,then set the corresponding attributes for output
 * 
 * @author ETCORE GroupTalk Developers
 * 
 */
public class UserMessagesAction extends AbstractAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7350494721632883178L;
	// validate result
	public static final int ACCESS_ALLOWED = 0;
	public static final int ERROR = 1;

	// utility constants

	public static final String START_PID = "startpid";
	public static final String END_PID = "endpid";
	public static final String COMMENT_NUM = "commentNum";
	public static final String LAST_COMMENT = "lastComment";
	public static final String KEY = "key";
	public static final String DEFAULT_OPEN = "2";
	public static final String COMMUNITIES_MSG_SIZE = "communitiesMsgSize";
	public static final String BOOKMARKS_MSG_SIZE = "bookmarksMsgSize";
	public static final String REMINDERS_MSG_SIZE = "remindersMsgSize";
	public static final String INFO_MSG_SIZE = "infoMsgSize";
	public static final String NAV1_MSG_SIZE = "nav1MsgSize";
	public static final String NAV2_MSG_SIZE = "nav2MsgSize";

	@Override
	public int validate(HttpServletRequest request, HttpServletResponse response) {

		String userName = request.getParameter(PageConstants.TARGET_USERNAME);
		if (userName != null) {
			try {
				userName = new String(
						userName.getBytes(PageConstants.ENCODING_ISO88591),
						(PageConstants.ENCODING_UTF8));
			} catch (Exception e) {
				e.printStackTrace();
			}
			UserService userService = new UserService();
			User result = userService.findByUserName(userName);
			// System.out.println(result.getUserName());
			if (result != null) {
				request.setAttribute(PageConstants.TARGET_USER, result);
				return ACCESS_ALLOWED;
			}
		}
		return ERROR;

	}

	@Override
	public String getForward(HttpServletRequest request, int validationResult) {
		if (ERROR == validationResult)
			return PageConstants.ACTION_PATH_ERROR;

		return PageConstants.PAGE_PATH_USERMESSAGES;
	}

	@Override
	public String getRedirect(HttpServletRequest request, int validationResult) {
		// TODO Auto-generated method stub

		return null;
	}

	@Override
	public void execute(int validationResult, HttpServletRequest request,
			HttpServletResponse response) {

		if (ACCESS_ALLOWED == validationResult)

			getMessages(request, response);

	}

	/*
	 * Integer tempm_id=(Integer)tempm[0]; Integer tempm_tid=(Integer)tempm[1];
	 * String tempm_name=(String)tempm[2]; String *
	 * tempm_addtime=(String)tempm[3]; String tempm_userName=(String)tempm[4];
	 * Integer tempm_num=(Integer)tempm[5]; Integer tempm_up=(Integer)tempm[6];
	 * Integer tempm_flag=(Integer)tempm[7]; String tempm_tag=(String)tempm[8];
	 * String tempm_source=(String)tempm[9]; String
	 * tempm_stime=(String)tempm[10]; Integer
	 * commentNum=gmessdao.findCommentNum(tempm_id); Gcomment
	 * tmpG=gmessdao.findLastComment(tempm_id);
	 */
	private void getMessages(HttpServletRequest request,
			HttpServletResponse response) {
		int intpageid = 1;

		String open = request.getParameter(PageConstants.OPEN);
		User targetUser = (User) request
				.getAttribute(PageConstants.TARGET_USER);

		// boolean isAdmin = (Boolean)
		// request.getAttribute(PageConstants.ISADMIN);
		MessageService msgService = new MessageService();
		long size = 0, intOpen = 2;
		long targetUserInfoMsgSize = 0, targetUserNav1MsgSize = 0, targetUserCommunitiesMsgSize = 0, targetUserNav2MsgSize = 0, targetUserBookmarksMsgSize = 0, targetUserRemindersMsgSize = 0;

		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P1)))

			targetUserInfoMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, targetUser.getUserName(),
					new Integer(1), 0);

		if (!PageConstants.ZERO.equals(Config.getConfig().getProperty(
				Config.P11)))
			targetUserNav1MsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, targetUser.getUserName(),
					new Integer(1), 1);
		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P2)))
			targetUserCommunitiesMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, targetUser.getUserName(),
					new Integer(2), 0);
		if (!PageConstants.ZERO.equals(Config.getConfig().getProperty(
				Config.P22)))
			targetUserNav2MsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, targetUser.getUserName(),
					new Integer(2), 1);
		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P3)))
			targetUserBookmarksMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, targetUser.getUserName(),
					new Integer(3));
		if (!PageConstants.ZERO.equals(Config.getConfig()
				.getProperty(Config.P4)))
			targetUserRemindersMsgSize = msgService.findSizeOfMessages(
					PageConstants.USERNAME, targetUser.getUserName(),
					new Integer(4));

		request.setAttribute(COMMUNITIES_MSG_SIZE, targetUserCommunitiesMsgSize);
		request.setAttribute(NAV2_MSG_SIZE, targetUserNav2MsgSize);
		request.setAttribute(BOOKMARKS_MSG_SIZE, targetUserBookmarksMsgSize);
		request.setAttribute(REMINDERS_MSG_SIZE, targetUserRemindersMsgSize);

		request.setAttribute(INFO_MSG_SIZE, targetUserInfoMsgSize);
		request.setAttribute(NAV1_MSG_SIZE, targetUserNav1MsgSize);
		if (size < targetUserInfoMsgSize) {
			size = targetUserInfoMsgSize;
			intOpen = 1;
		}

		if (open == null) {
			if (size < targetUserBookmarksMsgSize) {
				size = targetUserBookmarksMsgSize;
				intOpen = 3;
			}
			if (size < targetUserRemindersMsgSize) {
				size = targetUserRemindersMsgSize;
				intOpen = 4;
			}
			if (size < targetUserCommunitiesMsgSize) {
				size = targetUserCommunitiesMsgSize;
				intOpen = 2;
			}
			request.setAttribute(PageConstants.OPEN, intOpen);
			open = Symbols.BLANK + intOpen;
		}

		String key = request.getParameter(KEY);

		String nav = request.getParameter(PageConstants.NAV);
		if (nav == null)
			nav = PageConstants.ZERO;
		int unit = 10;
		@SuppressWarnings("rawtypes")
		List msgs = null;
		long all = 0;
		int begin = 0, pagenums = 0;
		String pageid = request.getParameter(PageConstants.PAGEID);
		Integer openInteger = new Integer(open);
		if (pageid != null)
			intpageid = Integer.parseInt(pageid);
		if (key != null && !Symbols.BLANK.equals(key))
			all = msgService.searchSizeByPropertyAndUserName(
					PageConstants.NAME, key, targetUser.getUserName());
		else {
			if (open != null && nav != null)
				all = msgService
						.findSizeOfMessages(PageConstants.USERNAME,
								targetUser.getUserName(), openInteger,
								new Integer(nav));
			else if (open != null)
				all = msgService.findSizeOfMessages(PageConstants.USERNAME,
						targetUser.getUserName(), openInteger);
		}
		pagenums = (int) ((all + unit - 1) / unit);
		begin = unit * (intpageid - 1);
		if (key != null && !Symbols.BLANK.equals(key))
			msgs = msgService.searchByPropertyAndUserName(PageConstants.NAME,
					key, targetUser.getUserName(), begin, unit);
		else {

			if (open != null && nav != null)
				msgs = msgService.findMessages(PageConstants.USERNAME,
						targetUser.getUserName(), openInteger,
						new Integer(nav), begin, unit);
			else if (open != null)
				msgs = msgService.findMessages(PageConstants.USERNAME,
						targetUser.getUserName(), openInteger, begin, unit);
		}
		if (msgs == null)
			return;
		int startpid = intpageid - 3;
		if (startpid <= 0)
			startpid = 1;
		int endpid = intpageid + 8;
		if (intpageid > 8)
			endpid = intpageid + 6;
		if (endpid >= pagenums)
			endpid = pagenums;

		request.setAttribute(START_PID, startpid);
		request.setAttribute(END_PID, endpid);
		AttachmentService attachmentService = new AttachmentService();
		// comment count and time
		for (int k = 0; k < msgs.size(); k++) {
			Object[] tempm = (Object[]) msgs.get(k);
			Integer tempm_id = (Integer) tempm[0];
			Long commentNum = msgService.findCommentNum(tempm_id);
			Comment tmpG = msgService.findLastComment(tempm_id);
			request.setAttribute(tempm_id + COMMENT_NUM, commentNum);

			if (tmpG != null)
				request.setAttribute(tempm_id + LAST_COMMENT, tmpG.getTime());
			List<Attachment> attachments = attachmentService.findByProperty(
					PageConstants.GMID, tempm_id);

			if (attachments != null) {
				List<String> images = new ArrayList<String>();
				for (Attachment attachment : attachments) {
					String attached = attachment.getAttached();
					if (attached.endsWith("jpg") || attached.endsWith("JPG")
							|| attached.endsWith("gif")
							|| attached.endsWith("GIF")
							|| attached.endsWith("bmp")
							|| attached.endsWith("BMP")
							|| attached.endsWith("png")
							|| attached.endsWith("PNG"))
						images.add(attached);
				}
				request.setAttribute(tempm_id + "attachments", images);
			}
		}
		request.setAttribute(
				"userMessagesCount",
				(targetUserInfoMsgSize + targetUserNav1MsgSize
						+ targetUserNav2MsgSize + targetUserCommunitiesMsgSize
						+ targetUserBookmarksMsgSize + targetUserRemindersMsgSize));
		request.setAttribute(PageConstants.MSGS, msgs);
		request.setAttribute(PageConstants.PAGENUMS, pagenums);
		request.setAttribute(PageConstants.ALL, all);
		request.setAttribute(PageConstants.UNIT, unit);
		request.setAttribute(PageConstants.INTPAGEID, intpageid);

	}

	@Override
	public boolean isForward(int validationResult) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean enablePostLoad() {
		// TODO Auto-generated method stub
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see etcore.webapp.grouptalk.controller.action.AbstractAction#
	 * buildSelfContextAndAttributes(int, javax.servlet.http.HttpServletRequest)
	 */
	@Override
	public List<String> getNamespacesOfMessages(HttpServletRequest request) {
		// TODO Auto-generated method stub
		List<String> namespaces = new ArrayList<String>();
		namespaces.add(MessageNamespaces.USER_PROFILE);
		return namespaces;
	}

}
